<template>
  <div>
    <a-card size="small" style="margin-bottom: 10px">
      <template #title>
        <div class="text-title">保证金详情</div>
      </template>
      <a-table
        :dataSource="bondData"
        :columns="bondColumns"
        :pagination="false"
        :loading="bondLoading"
        rowKey="id"
      >
        <template #headerCell="{ title, column }">
          <template v-if="column.key === 'leftPayment'">
            <span> 余额 </span>
            <TextTip
              :tips="['余额=（转入金额+实收金额-转出金额）- 已退金额']"
            />
          </template>
          <template v-if="column.key === 'overtimePayment'">
            <span> 欠费 </span>
            <TextTip
              :tips="['欠费=应收金额-实收金额-转入金额']"
            />
          </template>
        </template>
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key == 'index'">
            <span :class="record.type == 'total' ? 'total-row' : ''">{{text}}</span>
          </template>
          <template v-if="['receivePrice', 'actualPayment', 'refundPayment', 'leftPayment', 'overtimePayment', 'into_amount', 'out_amount'].includes(column.key)">
            <span>￥{{text}}</span>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-card size="small" class="year-card">
      <template #title>
        <div class="text-title">费用详情</div>
      </template>
      <a-spin :spinning="allLoading">
        <div class="year-card-tab">
          <a-tabs v-model:activeKey="activeKey" type="card" @change="handleTabChange">
            <a-tab-pane v-for="(tabItem) in allTabs" :key="tabItem.cost_type" :tab="tabItem.cost_type_txt"></a-tab-pane>
          </a-tabs>
        </div>
        <div class="year-card-body">
          <a-table
            :dataSource="yearData"
            :columns="yearColumns"
            :pagination="false"
            :rowClassName="rowClassNameFun"
            :customRow="customRow"
            rowKey="id"
          >
            <template #title>
              <div class="bold-title">年度总览</div>
            </template>
            <template #headerCell="{ title, column }">
              <template v-if="column.key === 'total_amount'">
                <span> 合同总金额 </span>
                <TextTip
                  :tips="['合同应收金额']"
                />
              </template>
              <template v-if="column.key === 'discount_amount'">
                <span> 合同内减免金额 </span>
                <TextTip
                  :tips="['合同优惠条款减免']"
                />
              </template>
              <template v-if="column.key === 'receivable_payment'">
                <span> 当年累计应收金额 </span>
                <TextTip
                  :tips="['合同应收-合同内减免']"
                />
              </template>
              <template v-if="column.key === 'adjust'">
                <span> 当年累计{{yearAdjustTitle}}金额 </span>
                <TextTip
                  :tips="[`账单${yearAdjustTitle}金额`]"
                />
              </template>
              <template v-if="column.key === 'notice_receive_payment'">
                <span> 当年累计缴费通知单应收金额 </span>
                <TextTip
                  :tips="['合同应收-合同内减免-日常账单手工调减金额']"
                />
              </template>
            </template>

            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.key == 'index'">
                <caret-right-outlined  :class="record.year == currentYear ? 'current-year-icon' : 'current-year-icon-trans'"/>
                <span :class="record.type == 'total' ? 'total-row' : ''">{{text}}</span>
              </template>
              <template v-if="['total_amount', 'discount_amount', 'receivable_payment', 'notice_receive_payment', 'actual_payment', 'overtime_payment'].includes(column.key)">
                <span>￥{{text}}</span>
              </template>
              <template v-if="column.key == 'adjust'">
                <template v-if="Number(record.adjust_sub) || Number(record.adjust_add)">
                  <span style="margin: 0 4px" v-if="Number(record.adjust_sub)">调减￥{{record.adjust_sub}}</span>
                  <span style="margin: 0 4px" v-if="Number(record.adjust_add)">调增￥{{record.adjust_add}}</span>
                </template>
                <span v-else>--</span>
              </template>
            </template>
          </a-table>

          <a-table
            v-if="currentYear"
            :dataSource="yearDetailData"
            :columns="yearDetailColumns"
            :pagination="false"
            :loading="yearDetailLoading"
            rowKey="id"
          >
            <template #title>
              <div class="bold-title">
                {{currentYear}}年度明细
                <span class="tips-title">点击上面年份查看具体年度明细</span>
              </div>
            </template>
            <template #headerCell="{ title, column }">
              <template v-if="column.key === 'adjust'">
                <span> {{yearDetailAdjustTitle}}金额 </span>
              </template>
            </template>
            <template #bodyCell="{ text, record, index, column }">
              <template v-if="['total_amount', 'discount_payment', 'receivable_payment', 'notice_receive_payment', 'actual_payment', 'overtime_payment', 'into_amount', 'out_amount', 'actual_retreat'].includes(column.key)">
                <span>￥{{text}}</span>
              </template>
              <template v-if="column.key == 'adjust'">
                <template v-if="Number(record.adjust_sub) || Number(record.adjust_add)">
                  <span style="margin: 0 4px" v-if="Number(record.adjust_sub)">调减￥{{record.adjust_sub}}</span>
                  <span style="margin: 0 4px" v-if="Number(record.adjust_add)">调增￥{{record.adjust_add}}</span>
                </template>
                <span v-else>--</span>
              </template>
            </template>
          </a-table>
        </div>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import {defineComponent, watch, computed, reactive, toRefs} from "vue";
import {
  CaretRightOutlined,
  ExclamationCircleOutlined,
  EditOutlined,
} from "@ant-design/icons-vue";
import { useRoute } from "vue-router";
import store from "../../../store/index";
import request from "@/common/utils/request";
import _ from "lodash";
import { TextTip } from "bl-common-vue3";

export default defineComponent({
  name: "ContractAnalyzeDetail",
  props: {
    active: {
      type: Boolean,
      default: false,
    },
    showType: {
      type: String,
      default: '',
    },
    drawerId: {
      type: [Number, String],
      default: '',
    },
  },
  components: { CaretRightOutlined, ExclamationCircleOutlined, EditOutlined, TextTip },
  setup(props, context) {
    const $route = useRoute();
    const id = computed(() => props.showType === 'drawer' ? Number(props.drawerId) : Number($route.query.id));

    const state = reactive({
      bondData: [],
      bondColumns: BOND_COLUMNS,
      bondLoading: false,
      allTabs: [],
      yearColumns: YEAR_COLUMNS,
      yearData: [],
      yearDetailColumns: YEAR_DETAIL_COLUMNS,
      yearDetailData: [],
      allLoading: false,
      yearDetailLoading: false,
      activeKey: undefined,
      currentYear: undefined,
      currentParams: {},
    })

    const yearAdjustTitle = computed(() => {
      let title = '调整';
      if (state.yearData.every((v) => !Number(v?.adjust_add))) {
        title = '调减';
      }
      return title;
    });

    const yearDetailAdjustTitle = computed(() => {
      let title = '调整';
      if (state.yearDetailData.every((v) => !Number(v?.adjust_add))) {
        title = '调减';
      }
      return title;
    });

    const getBondData = () => {
      state.bondLoading = true;
      request.get("/org", "/contract/bond/detail", {id: id.value}).then((res) => {
        state.bondLoading = false;
        state.bondData = res?.list || [];
      }).catch(() => {
        state.bondLoading = false;
      });
    };

    const getYearDetailData = () => {
      state.yearDetailLoading = true;
      let params = {
        id: id.value,
        year: state.currentYear,
      }
      if (state.activeKey && state.activeKey !== 'all') {
        params.cost_type = state.activeKey;
      }
      state.currentParams = _.cloneDeep(params);
      request.get("/org", "/contract/bill/order/detail", params).then((res) => {
        if (!_.isEqual(params, state.currentParams)) {
          return;
        }
        state.yearDetailData = res?.list || [];
        state.yearDetailLoading = false;
        state.allLoading = false;
      }).catch(() => {
        state.yearDetailLoading = false;
        state.allLoading = false;
      })
    };

    const getYearData = () => {
      state.allLoading = true;
      let params = {
        id: id.value,
      }
      if (state.activeKey && state.activeKey !== 'all') {
        params.cost_type = state.activeKey;
      }
      request.get("/org", "/contract/bill_order/detail", params).then((res) => {
        state.yearData = res?.list || [];
        if (!(state.currentYear && state.yearData.find((v) => v.year == state.currentYear))) {
          // 没选或者选项消失了
          state.currentYear = state.yearData[0]?.year || undefined;
        }
        if (state.currentYear) {
          getYearDetailData();
        } else {
          state.allLoading = false;
        }
      }).catch(() => {
        state.allLoading = false;
      });
    };

    const getTypes = () => {
      return new Promise((resolve, reject) => {
        state.allLoading = true;
        request.get("/org", "/contract/bill/cost_type", {id: id.value}).then((res) => {
          let list = res?.list;
          list.unshift({
            cost_type: 'all',
            cost_type_txt: '全部',
          })
          state.allTabs = list;
          if (!(state.activeKey && state.allTabs.find((v) => v.cost_type == state.activeKey))) {
            // 没有 active 或者 选择的类型 已经不在了
            state.activeKey = state.allTabs[0].cost_type;
          }
          resolve();
        }).catch(() => {
          state.allLoading = false;
          reject();
        });
      });
    };

    const rowClassNameFun = (record, index) => {
      if (record?.year == state.currentYear) {
        return "current-year-row have-year";
      }
      if (record?.type !== 'total') {
        return "have-year";
      }
    };

    const onYearRowClick = (record) => {
      if (record?.type !== 'total') {
        state.currentYear = record?.year;
        getYearDetailData();
      }
    };

    const customRow = (record) => {
      return {
        onClick: (e) => onYearRowClick(record),
      };
    };

    const handleTabChange = (e) => {
      getYearData();
    };


    watch(
      () => props.active,
      (val) => {
        if (val) {
          getBondData();
          getTypes().then(() => {
            getYearData();
          })
        }
      }
    );

    return {
      ...toRefs(state),
      yearAdjustTitle,
      yearDetailAdjustTitle,
      rowClassNameFun,
      customRow,
      handleTabChange,
    };
  },
});

const BOND_COLUMNS = [
  {
    title: "序号",
    dataIndex: "index",
    key: "index",
    width: "14%",
    align: "center",
  },
  {
    title: "费用名称",
    dataIndex: "costTypeDesc",
    key: "costTypeDesc",
    width: "16%",
    align: "center",
  },
  {
    title: "应收金额",
    dataIndex: "receivePrice",
    key: "receivePrice",
    width: "10%",
    align: "center",
  },
  {
    title: "实收金额",
    dataIndex: "actualPayment",
    key: "actualPayment",
    width: "10%",
    align: "center",
  },
  {
    title: "转入金额",
    dataIndex: "into_amount",
    key: "into_amount",
    width: "10%",
    align: "center",
  },
  {
    title: "转出金额",
    dataIndex: "out_amount",
    key: "out_amount",
    width: "10%",
    align: "center",
  },
  {
    title: "欠费",
    dataIndex: "overtimePayment",
    key: "overtimePayment",
    width: "10%",
    align: "center",
  },
  {
    title: "已退金额",
    dataIndex: "refundPayment",
    key: "refundPayment",
    width: "10%",
    align: "center",
  },
  {
    title: "余额",
    dataIndex: "leftPayment",
    key: "leftPayment",
    width: "10%",
    align: "center",
  },
];

const YEAR_COLUMNS = [
  {
    title: "序号",
    dataIndex: "index",
    key: "index",
    width: "7%",
    align: "center",
  },
  {
    title: "年度",
    dataIndex: "year",
    key: "year",
    width: "8%",
    align: "center",
  },
  {
    title: "合同总金额",
    dataIndex: "total_amount",
    key: "total_amount",
    width: "12%",
    align: "center",
  },
  {
    title: "合同内减免金额",
    dataIndex: "discount_amount",
    key: "discount_amount",
    width: "10%",
    align: "center",
  },
  {
    title: "当年累计应收金额",
    dataIndex: "receivable_payment",
    key: "receivable_payment",
    width: "12%",
    align: "center",
  },
  {
    title: "当年累计调整金额",
    dataIndex: "adjust",
    key: "adjust",
    width: "15%",
    align: "center",
  },
  {
    title: "当年累计缴费通知单应收金额",
    dataIndex: "notice_receive_payment",
    key: "notice_receive_payment",
    width: "16%",
    align: "center",
  },
  {
    title: "当年累计实收金额",
    dataIndex: "actual_payment",
    key: "actual_payment",
    width: "10%",
    align: "center",
  },
  {
    title: "当年累计欠费金额",
    dataIndex: "overtime_payment",
    key: "overtime_payment",
    width: "10%",
    align: "center",
  },
];

const YEAR_DETAIL_COLUMNS = [
  {
    title: "序号",
    dataIndex: "index",
    key: "index",
    width: 120,
    align: "center",
  },
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    key: "cost_type_txt",
    width: 130,
    align: "center",
  },
  {
    title: "费用期间",
    dataIndex: "date",
    key: "date",
    width: 160,
    align: "center",
  },
  {
    title: "合同总金额",
    dataIndex: "total_amount",
    key: "total_amount",
    width: 140,
    align: "center",
  },
  {
    title: "合同内减免金额",
    dataIndex: "discount_payment",
    key: "discount_payment",
    width: 140,
    align: "center",
  },
  {
    title: "应收金额",
    dataIndex: "receivable_payment",
    key: "receivable_payment",
    width: 130,
    align: "center",
  },
  {
    title: "合同约定的交费日",
    dataIndex: "receivable_payment_date",
    key: "receivable_payment_date",
    width: 120,
    align: "center",
  },
  {
    title: "调整金额",
    dataIndex: "adjust",
    key: "adjust",
    width: 180,
    align: "center",
  },
  {
    title: "缴费通知单应收",
    dataIndex: "notice_receive_payment",
    key: "notice_receive_payment",
    width: 130,
    align: "center",
  },
  {
    title: "实收金额",
    dataIndex: "actual_payment",
    key: "actual_payment",
    width: 120,
    align: "center",
  },
  {
    title: "转入金额",
    dataIndex: "into_amount",
    key: "into_amount",
    width: 120,
    align: "center",
  },
  {
    title: "转出金额",
    dataIndex: "out_amount",
    key: "out_amount",
    width: 120,
    align: "center",
  },
  {
    title: "需收金额",
    dataIndex: "actual_retreat",
    key: "actual_retreat",
    width: 120,
    align: "center",
  },
  {
    title: "欠费金额",
    dataIndex: "overtime_payment",
    key: "overtime_payment",
    width: 120,
    align: "center",
  },
]
</script>

<style lang="less" scoped>
@colHeight: 40px;
.clause-detail {
  margin-bottom: 10px;
  .alert {
    margin: 0 10px 10px 10px;
  }
  &:deep(.ant-alert) {
    padding: 4px 16px;
  }
  &:deep(.ant-card-body) {
    padding: 0;
  }
  .header {
    background: @primary-color-bg;
  }
  .cols {
    line-height: @colHeight;
    padding: 0 12px;
  }
  .cl-footer {
    text-align: right;
    color: rgba(0, 0, 0, 0.8);
  }
}
:deep(.ant-card-head-title) {
  padding: 0!important;
}
.year-card {
  :deep(.ant-card-body) {
    padding: 0 0 12px 0;
  }
  :deep(.ant-card-head) {
    border-bottom: none;
  }
  :deep(.ant-table-title) {
    padding: 0;
  }
}
.year-card-tab {
  padding: 0 12px;
  border-bottom: 1px solid #f0f0f0;
}
.year-card-body {
  padding: 0 12px;
}
.bold-title {
  font-weight: bold;
  font-size: 14px;
  padding: 12px 0;
}
.tips-title {
  font-size: 12px;
  color: #999;
}
.total-row {
  font-weight: bold;
}
:deep(.ant-table-thead > tr > th) {
  background: #f0f9ff;
}
:deep(.current-year-row){
  background: #e0e0e0;
}
:deep(.current-year-row td){
  background-color: #e0e0e0!important;
}
:deep(.have-year) {
  cursor: pointer;
}
.current-year-icon-trans {
  opacity: 0;
  margin-right: 4px;
}
.current-year-icon {
  opacity: 1;
  color: @primary-color;
  margin-right: 4px;
}
:deep(.ant-table-tbody > tr:last-child td) {
  border-bottom: none;
}
</style>
